package com.example.springbootsecurity.demos.web;

import cn.hutool.core.map.MapUtil;
import com.example.springbootsecurity.demos.common.Constant;
import com.example.springbootsecurity.demos.common.Result;
import com.example.springbootsecurity.demos.util.RedisUtil;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author by jingwei
 * @version V1.0
 * @classname KaptchaController
 * @description
 * @date 2023/12/4 16:57
 */
@Controller
public class CaptchaController {

    @Autowired
    private Producer producer;

    @Autowired
    private RedisUtil redisUtil;

    @GetMapping("/captcha")
    public Result captcha() throws IOException {
        String key = UUID.randomUUID().toString();
        String code = producer.createText();

        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);

        BASE64Encoder encoder = new BASE64Encoder();
        String str = "data:image/jpeg;base64,";

        String base64Img = str + encoder.encode(outputStream.toByteArray());

        redisUtil.setEx(Constant.CAPTCHA_KEY, key, 180, TimeUnit.SECONDS);

        return Result.succ(
                MapUtil.builder()
                        .put("userKey", key)
                        .put("captcha", base64Img)
                        .build()
        );
    }
}
